package it.csi.finregio.finreges.client.printers;

import it.csi.finregio.finreges.util.SchedaData;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;

public class PdfPrinter implements Printer {

	public InputStream print(Object data) throws Exception{
		Collection dataToPrint = (Collection) data;
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		Document document = new Document();
		PdfWriter pdfWriter = PdfWriter.getInstance(document, bout);

		document.open();
		for (Iterator iterator = dataToPrint.iterator(); iterator.hasNext();) {
			document.newPage();
			SchedaData d = (SchedaData) iterator.next();

			ArrayList l = HTMLWorker.parseToList(new StringReader(d
					.toString()), null);

			for (Iterator it = l.iterator(); it.hasNext();) {
				Element el = (Element) it.next();
				document.add(el);

			}
		}
		document.close();
		return new ByteArrayInputStream(bout.toByteArray());
	}

}
